import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from datetime import datetime, timedelta
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split

from config.settings import EXCHANGES, RiskConfig, AnalysisConfig
from backtest.engine import BacktestEngine
from backtest.data_handler import HistoricalDataHandler
from strategies.ml_enhanced_strategy import MLEnhancedStrategy
from analysis.market_analyzer import MarketAnalyzer
from analysis.chain_analyzer import ChainAnalyzer
from analysis.sentiment_analyzer import SentimentAnalyzer
from analysis.technical_indicators import TechnicalIndicators
from risk.risk_manager import RiskManager
from analysis.ml_predictor import MLPredictor
from utils.visualization import plot_backtest_results

def prepare_ml_model(market_data: pd.DataFrame) -> MLPredictor:
    """准备和训练机器学习模型"""
    # 创建技术指标
    ti = TechnicalIndicators()
    features = ti.calculate_all_indicators(market_data)
    
    # 准备标签（未来24小时的价格变动）
    features['target'] = market_data['close'].pct_change(24).shift(-24)
    
    # 删除包含NaN的行
    features = features.dropna()
    
    # 分割特征和标签
    X = features.drop(['target'], axis=1)
    y = (features['target'] > 0).astype(int)  # 二元分类：上涨或下跌
    
    # 分割训练集和测试集
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.2, shuffle=False
    )
    
    # 创建和训练模型
    ml_predictor = MLPredictor()
    ml_predictor.train(X_train, y_train)
    
    # 打印模型性能
    train_score = ml_predictor.evaluate(X_train, y_train)
    test_score = ml_predictor.evaluate(X_test, y_test)
    print(f"训练集准确率: {train_score:.2f}")
    print(f"测试集准确率: {test_score:.2f}")
    
    return ml_predictor

def main():
    # 设置回测参数
    start_date = datetime(2023, 1, 1)
    end_date = datetime(2023, 12, 31)
    symbol = 'BTC/USDT'
    timeframe = '1h'
    initial_capital = 100000.0
    
    try:
        # 获取历史数据
        data_handler = HistoricalDataHandler(
            exchanges={'okx': EXCHANGES['okx']},
            symbols=[symbol],
            start_date=start_date,
            end_date=end_date,
            timeframe=timeframe
        )
        market_data = data_handler.get_historical_data(symbol)
        
        # 准备分析组件
        market_analyzer = MarketAnalyzer(config=AnalysisConfig())
        chain_analyzer = ChainAnalyzer()
        sentiment_analyzer = SentimentAnalyzer()
        risk_manager = RiskManager(config=RiskConfig())
        
        # 准备和训练ML模型
        print("训练机器学习模型...")
        ml_predictor = prepare_ml_model(market_data)
        
        # 创建ML增强策略
        strategy = MLEnhancedStrategy(
            market_analyzer=market_analyzer,
            chain_analyzer=chain_analyzer,
            sentiment_analyzer=sentiment_analyzer,
            risk_manager=risk_manager,
            ml_predictor=ml_predictor,
            lookback_period=24,
            short_window=5,
            long_window=20,
            rsi_period=14,
            rsi_overbought=70,
            rsi_oversold=30,
            volatility_window=20,
            position_size=0.1,
            stop_loss=0.02,
            take_profit=0.04
        )
        
        # 创建回测引擎
        engine = BacktestEngine(
            data_handler=data_handler,
            strategy=strategy,
            risk_manager=risk_manager,
            initial_capital=initial_capital
        )
        
        # 运行回测
        print("\n开始回测...")
        engine.run_backtest()
        
        # 获取回测结果
        results = engine.get_backtest_results()
        
        # 打印回测结果
        print("\n=== 回测结果 ===")
        print(f"初始资金: ${results['Initial Capital']:,.2f}")
        print(f"最终资金: ${results['Final Capital']:,.2f}")
        print(f"总收益率: {results['Total Return']*100:.2f}%")
        print(f"年化收益率: {results['Annual Return']*100:.2f}%")
        print(f"夏普比率: {results['Sharpe Ratio']:.2f}")
        print(f"最大回撤: {results['Max Drawdown']*100:.2f}%")
        print(f"胜率: {results['Win Rate']*100:.2f}%")
        print(f"总交易次数: {results['Total Trades']}")
        print(f"盈利交易: {results['Winning Trades']}")
        print(f"亏损交易: {results['Losing Trades']}")
        print(f"平均盈利: ${results['Average Win']:,.2f}")
        print(f"平均亏损: ${results['Average Loss']:,.2f}")
        print(f"总手续费: ${results['Total Commission']:,.2f}")
        
        # 可视化回测结果
        plot_backtest_results(results)
        
        # 保存详细结果
        results['Positions History'].to_csv('ml_backtest_positions.csv')
        results['Holdings History'].to_csv('ml_backtest_holdings.csv')
        print("\n详细结果已保存到 ml_backtest_positions.csv 和 ml_backtest_holdings.csv")
        
    except Exception as e:
        print(f"回测过程中出错: {str(e)}")
        raise

if __name__ == "__main__":
    main()
